package cn.zxf.note.security.platform;

import cn.zxf.note.common.exception.BizException;
import cn.zxf.note.security.TokenUtils;
import cn.zxf.note.user.platform.PlatformEnum;
import cn.zxf.note.user.platform.UserPlatform;
import cn.zxf.note.user.platform.UserPlatformSupport;
import cn.zxf.note.user.user.User;
import cn.zxf.note.user.user.UserRepository;
import cn.zxf.note.user.user.UserStatusEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * Created by zengxf on 2020/3/25.
 */
@Slf4j
public abstract class AbstractPlatformLoginService implements PlatformLoginService {

    @Getter
    protected PlatformEnum platform;
    @Autowired
    protected UserPlatformSupport userPlatformSupport;
    @Autowired
    protected UserRepository userRepos;

    public AbstractPlatformLoginService(PlatformEnum platform) {
        this.platform = platform;
    }

    protected LoginResult login(String openId) {
        LoginResult result = new LoginResult()
                .setOpenId(openId);
        UserPlatform up = userPlatformSupport.findOne(platform.code, openId);
        if (up != null) {
            User user = userRepos.findById(up.getUserId()).orElse(new User());
            if (!Objects.equals(user.getStatus(), UserStatusEnum.NORMAL.code)) {
                throw BizException.of("账号已冻结");
            } else {
                String token = TokenUtils.generate(up.getUserId(), true);
                result.setSign(LoginResult.SIGN_OK)
                        .setToken(token)
                        .setMessage("登录成功");
            }
        } else {
            result.setSign(LoginResult.SIGN_GENERAL)
                    .setMessage("还没关联账号");
        }
        return result;
    }

}
